import React, { useEffect, useState, useContext, useMemo } from 'react';
import { ShareAltOutlined, UploadOutlined } from "@ant-design/icons";
import TextArea from "antd/es/input/TextArea";
import moment from 'moment';
import {
  message,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Table,
  Typography,
  Upload,
  DatePicker,
  InputNumber,
  Spin,
  Cascader,
} from "antd";
import { useTranslation } from 'react-i18next';

import { createBidding, getBidding, inviteBiddingApi, getUserListApi } from '@src/services/biddingProject';
import { uploadALiFile } from '@src/services/user';
import { PublicDataStore } from '@src/store/PublicData/Provider';
import { formatTimeDifference } from '@src/utils/dataHandlingFunc';

import styles from './styles.module.less';
const { Title, Paragraph, Text, Link } = Typography;

const MyMarket = () => {
  const { t } = useTranslation();
  const { state } = useContext(PublicDataStore);

  const [biddingData, setBiddingData] = useState([]);
  const [getLoading, setGetLoading] = useState(false);
  const [userList, setUserList] = useState([]);
  const [requirementModalVisible, setRequirementModalVisible] = useState(false);
  const [biddingSubmitLoading, setBiddingSubmitLoading] = useState(false);
  const [biddingRowKey, setBiddingRowKey] = useState([]);
  const [biddingRowData, setBiddingRowData] = useState({});
  const [inviteBiddingModalVisible, setInviteBiddingModalVisible] = useState(false);
  const [inviteBiddingLoading, setInviteBiddingLoading] = useState(false);

  useEffect(() => {
    onLoad();
    onGetUserListLoad();
  }, [])

  const onLoad = async () => {
    setGetLoading(true);
    const res = await getBidding();

    if (!res) return;
    setGetLoading(false);
    setBiddingData(res || []);

    if ((!biddingRowKey[0]) && res.length) {
      const defaultSelectRowData = res?.filter(item => item.state === 10) || [];

      setBiddingRowKey(defaultSelectRowData.length ? [defaultSelectRowData?.[0]?.tender_id] : []);
      setBiddingRowData(defaultSelectRowData?.[0] || {});
    }
  }

  const onGetUserListLoad = async () => {
    const res = await getUserListApi();

    if (!res) return;
    console.log(res)
    setUserList(res);
  }

  const onBiddingProjectFinish = async (data) => {
    setBiddingSubmitLoading(true);

    let ossRes = '';
    if(data.attachments?.fileList?.length){
       ossRes = await uploadALiFile(data.attachments?.fileList?.map(item => item.response), 'tender');
    }

    const res = await createBidding({
      ...data,
      source: data.source[data.source.length - 1],
      destination: data.destination[data.destination.length - 1],
      // attachments: data.attachments?.fileList || []
      attachments: ossRes ? JSON.stringify(ossRes) : []
    });

    setBiddingSubmitLoading(false);

    if (res.code === 0) {
      message.success(res.message);
      onLoad();
      setRequirementModalVisible(false);
    }
  }

  // 邀请投标
  const onInviteBiddingFinish = async (data) => {
    setInviteBiddingLoading(true);

    const res = await inviteBiddingApi({
      tender_id: biddingRowKey[0],
      user: data.user
    });

    setInviteBiddingLoading(false);
    if (res.code === 0) {
      message.success(res.message);
      onLoad();
      onCancelInviteBiddingModal();
    }
  }

  // 等待投标
  const pendingColumns = [
    {
      title: t('Title'),
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: t('Expiration time'),
      dataIndex: 'expiration_date',
      key: 'expiration_date',
      render: (_, record) => (
        <span>{formatTimeDifference(record.expiration_date)}</span>
      )
    },
    {
      title: t('State'),
      dataIndex: 'state',
      key: 'state',
      render: (_, record) => (
        <span>{t('Waiting for bidding')}</span>
      )
    },
  ];

  // 已收到投标
  const receivedColumns = [
    {
      title: t('Title'),
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: t('Expiration time'),
      dataIndex: 'expiration_date',
      key: 'expiration_date',
      render: (_, record) => (
        <span>{formatTimeDifference(record.expiration_date)}</span>
      )
    },
    {
      title: t('State'),
      dataIndex: 'bid_count',
      key: 'bid_count',
      render: (_, record) => (
        <span>{t('Received')}+{record.bid_count}</span>
      )
    },
  ];

  // 已完成投标
  const finishedColumns = [
    {
      title: t('Title'),
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: t('Expiration time'),
      dataIndex: 'expiration_date',
      key: 'expiration_date',
      render: (_, record) => (
        <span>{formatTimeDifference(record.expiration_date)}</span>
      )
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (_, record) => (
        <span>{t('Completed')}</span>
      )
    },
  ];

  const cityOptions = useMemo(() => {
    if (!(state.city.length && state.country.length)) return [];

    let countryMapCity = {};

    state.city.forEach(_city => {
      let newCity = {
        ..._city,
        label: _city?.[sessionStorage.getItem('ai_lang')],
        value: _city.city_id,
      };

      if (countryMapCity[_city.country_id]) {
        countryMapCity[_city.country_id] = [...countryMapCity[_city.country_id], newCity]
      } else {
        countryMapCity[_city.country_id] = [newCity]
      }
    });
 
    return state.country?.map(_country => ({
      value: _country.country_id,
      label: _country?.[sessionStorage.getItem('ai_lang')],
      disabled: !countryMapCity[_country.country_id]?.length,
      children: countryMapCity[_country.country_id]
    }))
  }, [state.city, state.country, t])

  const disabledDate = (current) => {
    // 禁用过期时间
    if (current < moment().add(0, 'days')) {
      return true;
    }

    return false;
  };

  const onBiddingSelectChange = (rowData) => {
    setBiddingRowKey([rowData.tender_id]);
    setBiddingRowData(rowData);
    console.log(rowData)
  }

  const onCancelInviteBiddingModal = () => {
    setInviteBiddingModalVisible(false);
  }

  return (
    <div className={styles.my_market}>
      <Divider orientation="left">
        <Button type="primary" onClick={() => setRequirementModalVisible(true)}>{t('Release bid')}</Button>
      </Divider>
      <Spin spinning={getLoading}>
        <Row gutter={16}>
          <Col span={12}>
            <Divider orientation="left">{t('Waiting for bids')}</Divider>
            <Table
              dataSource={biddingData.filter(item => item.state === 10)}
              columns={pendingColumns}
              pagination={{
                pageSize: 5,
                size: 'small'
              }}
              rowKey="tender_id"
              rowSelection={{
                selectedRowKeys: biddingRowKey,
                // onChange: onBiddingSelectChange,
                onSelect: onBiddingSelectChange,
                hideSelectAll: true,
                type: 'radio',
              }}
              onRow={record => {
                return {
                  onClick: () => {
                    onBiddingSelectChange(record)
                  }
                }
              }}
            />
            <Divider orientation="left">{t('Bids received')}</Divider>
            <Table
              dataSource={biddingData.filter(item => item.state === 20)}
              columns={receivedColumns}
              pagination={{
                pageSize: 5,
                size: 'small'
              }}
              rowKey="tender_id"
            />
            <Divider orientation="left">{t('Completed bidding items')}</Divider>
            <Table
              dataSource={biddingData.filter(item => item.state === 1)}
              columns={finishedColumns}
              pagination={{
                pageSize: 5,
                size: 'small'
              }}
              rowKey="tender_id"
            />
          </Col>
          <Col span={12} style={{ backgroundColor: '#fff', borderRadius: '20px', padding: '20px' }}>
            <Paragraph>
              <pre>{t('You can invite all suppliers on the site to participate in the bidding, or share the link with friends to participate in the bidding')}</pre>
            </Paragraph>

            <div className={styles.invite_span}>
              <span>
                {
                  !!biddingRowData.tender_id && (
                    <Button
                      type="primary"
                      loading={inviteBiddingLoading}
                      onClick={() => setInviteBiddingModalVisible(true)}
                    >
                      {t('Invitation to Bid')}
                    </Button>
                  )
                }
              </span>
              <span><ShareAltOutlined style={{ fontSize: '28px', color: '#08c', marginLeft: '20px' }} /></span>
            </div>

            <div className={styles.title}>
              {biddingRowData.title || ''}
            </div>
            <Divider orientation="left"></Divider>
            <div>
              <Row>
                <Col span={12}>
                  <p className={styles.little_desc}>{t('Source')}</p>
                  <p className={styles.little_content}>{biddingRowData?.source?.city?.[sessionStorage.getItem('ai_lang')] || ''}</p>
                </Col>
                <Col span={12}>
                  <p className={styles.little_desc}>{t('Destination')}</p>
                  <p className={styles.little_content}>{biddingRowData?.destination?.city?.[sessionStorage.getItem('ai_lang')] || ''}</p>
                </Col>
              </Row>

              <Row>
                <Col span={6}>
                  <p className={styles.little_desc}>{t('Cooperation period')}</p>
                  <p className={styles.little_content}>{biddingRowData?.expiration_date ? formatTimeDifference(biddingRowData?.expiration_date) : ''}</p>
                </Col>
                <Col span={6}>
                  <p className={styles.little_desc}>{t('Expected delivery time')}</p>
                  <p className={styles.little_content}>{biddingRowData?.expiration_date ? moment(biddingRowData?.expiration_date).format('YYYY/MM/DD') : ''}</p>
                </Col>
                <Col span={6}>
                  <p className={styles.little_desc}>{t('Bandwidth')}</p>
                  <p className={styles.little_content}>{biddingRowData?.bandwidth ? `${biddingRowData?.bandwidth} M` : ''}</p>
                </Col>
                <Col span={6}>
                  <p className={styles.little_desc}>{t('Access method')}</p>
                  <p className={styles.little_content}>{biddingRowData?.business_name || ''}</p>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <p className={styles.little_desc}>{t('Additional description')}</p>
                  <p className={styles.little_content}>{biddingRowData?.description || ''}</p>
                </Col>
              </Row>
            </div>

            <div>
              <Row>
                <Col span={12}>
                  <p className={styles.little_desc}>{t('Market')}</p>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Card style={{ width: 300 }}>
                    <Row>
                      <Col style={12}>
                        {
                          biddingRowData?.destination?.country?.national_flag && (
                            <img style={{ width: '80px' }} src={`/api${biddingRowData?.destination?.country?.national_flag}`} />
                          )
                        }
                      </Col>
                      <Col style={12}>
                        <p className={styles.little_desc} style={{ marginLeft: '10px', marginTop: '-5px' }}>{biddingRowData?.destination?.city?.[sessionStorage.getItem('ai_lang')]}</p>
                        <p className={styles.little_content} style={{ marginLeft: '10px' }}>{biddingRowData?.destination?.country?.[sessionStorage.getItem('ai_lang')]}</p>

                      </Col>
                    </Row>
                  </Card>
                </Col>
                {/* <Col span={12}>
                                    <Card style={{ width: 300 }}>
                                        <Row>
                                            <Col style={12}><img style={{ width: '80px' }} src='/img/dibaiFlag.jpg' /></Col>
                                            <Col style={12}>
                                                <p className={styles.little_desc} style={{ marginLeft: '10px', marginTop: '-5px' }}>迪拜</p>
                                                <p className={styles.little_content} style={{ marginLeft: '10px' }}>中东</p>

                                            </Col>
                                        </Row>
                                    </Card>
                                </Col> */}
              </Row>

            </div>

            {
              (biddingRowData?.attachments?.length > 0) && (
                <div>
                  <p className={styles.little_desc}>{t('Enclosure')}</p>
                  {
                    biddingRowData?.attachments?.map((item, index) => (
                      <p key={index}>
                        <a
                          className={styles.little_content}
                          href={item}
                          // download={item?.split('/')?.slice(-1)[0]}
                          download={t('Download')}
                          style={{ color: 'blue' }}
                          target="_blank"
                        >
                          {item?.split('/')?.slice(-1)[0]}
                        </a>
                      </p>
                    ))
                  }
                </div>
              )
            }

          </Col>
        </Row>
      </Spin>
      <Modal
        open={requirementModalVisible}
        footer={null}
        onCancel={() => setRequirementModalVisible(false)}
        style={{ minWidth: 650 }}
      >
        <div className={styles.requirement_modal_box}>
          <div className={styles.title}>{t('Create a new item')}</div>
          <div className={styles.form_box}>
            <Form layout="vertical" onFinish={onBiddingProjectFinish}>
              <Form.Item
                label={t('Title')}
                name="title"
                rules={[
                  {
                    required: true,
                    message: t('Please enter a title')
                  },
                ]}
              >
                <Input name="title" />
              </Form.Item>
              <Form.Item
                label={t('Specific description')}
                name="description"
                rules={[
                  {
                    required: true,
                    message: t('Please enter a detailed description')
                  },
                ]}
              >
                <TextArea name="description" />
              </Form.Item>
              <Form.Item
                label={t('Validity period')}
                name="expiration_date"
                rules={[
                  {
                    required: true,
                    message: t('Please select the effective time')
                  },
                ]}
              >
                <DatePicker
                  showTime
                  name='expiration_date'
                  disabledDate={disabledDate}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item
                label={t('Serve')}
                name="business_id"
                rules={[
                  {
                    required: true,
                    message: t('Please select a service')
                  },
                ]}
              >
                <Select name="business_id"  >
                  {state.companyInof?.company_business?.map(item => (
                    <Select.Option key={item.business_id} value={item.business_id}>{item.business_name}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                label={t('Targeting the market')}
                name="marketing"
                rules={[
                  {
                    required: true,
                    message: t('Please select market')
                  },
                ]}
              >
                <Select name="marketing">
                  {state.continent?.map(item => (
                    <Select.Option key={item.continent_id} value={item.zhCN}>{item?.[sessionStorage.getItem('ai_lang')]}</Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Row justify='space-between'>
                <Col span={11}>
                  <Form.Item
                    label={t('Source')}
                    name="source"
                    rules={[
                      {
                        required: true,
                        message: t('Please select the source city')
                      },
                    ]}
                  >
                    <Cascader
                      name="source"
                      displayRender={(labels) => labels[labels.length - 1]}
                      options={cityOptions}
                    />
                  </Form.Item>
                </Col>
                <Col span={11}>
                  <Form.Item
                    label={t('Destination')}
                    name="destination"
                    rules={[
                      {
                        required: true,
                        message: t('Please select the target city')
                      },
                    ]}
                  >
                    <Cascader
                      name="source"
                      displayRender={(labels) => labels[labels.length - 1]}
                      options={cityOptions}
                    />
                  </Form.Item>
                </Col>
              </Row>
              <Row justify='space-between'>
                <Col span={11}>
                  <Form.Item
                    label={t('Contract period (month)')}
                    name="contract"
                    rules={[
                      {
                        required: true,
                        message: t('Please select the contract period')
                      },
                    ]}
                  >
                    <InputNumber name="contract" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={11}>
                  <Form.Item
                    label={t('Bandwidth')}
                    name="bandwidth"
                    rules={[
                      {
                        required: true,
                        message: t('Please select bandwidth')
                      },
                    ]}
                  >
                    <InputNumber name="bandwidth" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>
              <Row justify='space-between'>
                <Col span={7}>
                  <Form.Item
                    label={t('Minimum budget')}
                    name="min_budget"
                    dependencies={['max_budget']}
                    rules={[
                      {
                        required: true,
                        message: t('Please enter a minimum budget')
                      },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (getFieldValue().max_budget < value) {
                            return Promise.reject(t('The minimum budget cannot be greater than the maximum budget'));
                          }

                          return Promise.resolve();
                        }
                      })
                    ]}
                  >
                    <InputNumber name="min_budget" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={7}>
                  <Form.Item
                    label={t('Maximum budget')}
                    name="max_budget"
                    dependencies={['min_budget']}
                    rules={[
                      {
                        required: true,
                        message: t('Please enter your maximum budget')
                      },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (getFieldValue().min_budget > value) {
                            return Promise.reject(t('The maximum budget cannot be less than the maximum budget'));
                          }

                          return Promise.resolve();
                        }
                      })
                    ]}
                  >
                    <InputNumber name="max_budget" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={7}>
                  <Form.Item
                    label={t('Unit')}
                    name="unit"
                    rules={[
                      {
                        required: true,
                        message: t('Please select a budget unit')
                      },
                    ]}
                  >
                    <Select name="unit">
                      <Select.Option value="年">{t('Year')}</Select.Option>
                      <Select.Option value="月">{t('Moon')}</Select.Option>
                      <Select.Option value="日">{t('Day')}</Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item label={t('Add attachments')} name="attachments">
                <Upload
                  name="attachments"
                  accept="image/png, image/jpeg, text"
                  headers={{
                    authorization: 'authorization-text',
                  }}
                  customRequest={file => file.onSuccess(file.file)}
                  multiple
                >
                  <Button icon={<UploadOutlined />}>{t('Click to Upload')}</Button>
                </Upload>
              </Form.Item>
              <div className={styles.footer_box}>
                <Button type='primary' htmlType='submit' loading={biddingSubmitLoading}>{t('Submit')}</Button>
              </div>
            </Form>
          </div>
        </div>
      </Modal>

      <Modal
        open={inviteBiddingModalVisible}
        footer={null}
        onCancel={onCancelInviteBiddingModal}
        title={t('Invitation to Bid')}
      >
        <div className={styles.invite_bidding_modal_box}>
          <Form layout="vertical" onFinish={onInviteBiddingFinish}>
            <Form.Item
              label={t('Invite users')}
              name="user"
              rules={[
                {
                  required: true,
                  message: t('Please select user')
                },
              ]}
            >
              <Select
                mode="multiple"
                name="user"
                allowClear
              >
                {
                  userList?.map(item => (
                    <Select.Option
                      key={item.user_id}
                      value={item.user_id}
                    >
                      {item.email}
                    </Select.Option>
                  ))
                }
              </Select>
            </Form.Item>
            <div className={styles.footer_box}>
              <Button type='ghost' onClick={onCancelInviteBiddingModal}>{t('Cancel')}</Button>
              <Button type='primary' htmlType='submit' loading={inviteBiddingLoading}>{t('Sure')}</Button>
            </div>
          </Form>
        </div>
      </Modal>
    </div>
  );
};

export default MyMarket;
